<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use EasyWeChat\Foundation\Application;

class UserController extends Controller
{
	public $app = null;
	// 在 __construct 中实例化 Application, 并赋给 $app 属性 , 便于在所有方法中引用
	public function __construct(){
		$options = [
			'debug' => true,
			'app_id' => 'wxccd4ba8c98e3d52a',
			'secret' => 'd4624c36b6795d1d99dcf0547af5443d',
			'token' => 'shifu203',
			// 'aes_key' => null, //  可选
			'log' => [
				'level' => 'debug',
				'file' => '/data/www/fenxiao/easywechat.log', //  绝对路径！！！！
				],
			// 用户回调页面
			'oauth' => [
				'scopes' => ['snsapi_userinfo'],
				'callback' => 'login',
			],
		];

		$this->app = new Application($options);
	}

	// 网页授权
	public function center(Request $req){
	// 判断如果没有用户登录跳转登录页面
		if(!$req->session()->has('wechat_user')){
			$oauth = $this->app->oauth;
			return $oauth->redirect();
		}
		$username = session()->get('wechat_user');
		// var_dump($username->original['nickname']);die;
		return " 欢迎". $username->original['nickname'] ."登录!";
	}

	public function login(){
		$oauth = $this->app->oauth;
		$user = $oauth->user();// 微信给我们提供用户信息
		session()->put('wechat_user',$user);// 用户信息存入 session
		// 登录成功调转商城中心
		return redirect('center');
	}



	public function logout(){
		// 用户退出清除 session
		session()->forget('wechat_user');

		return "登出成功";
	}

}
